
import moduleA from './modules/moduleA'
// 页面路径：store/index.js
import { createStore } from 'vuex'
const store = createStore({
	state: {
		cart:JSON.parse(uni.getStorageSync('cart')||'[]'),
    //收获地址数据
    // address:{}
    address:JSON.parse(uni.getStorageSync('address')||'{}'),
    token:'',
    //用户的信息对象
    userinfo:JSON.parse(uni.getStorageSync('userinfo')||'{}')
	},
	modules:{
    moduleA
  },
  getters: {
    addstr(state){
      if(!state.address.provinceName) return ''
      
      return state.address.provinceName+state.address.cityName+state.address.countyName+state.address.detailInfo
    },
    //购物车所有商品的总数量
    total(state){
      // let c=0
      // state.cart.forEach(x=>c+=x.goods_count)
      // return c
     return  state.cart.reduce((total,item)=>total+=item.goods_count,0)
    },
    checkedCount(state){
      //先使用filter方法，从购物车中过滤已经勾选的商品
      //在使用reduce方法，将已勾选的商品数量进行累加
      //reduce的返回值就是已经勾选的数量
     return  state.cart.filter(x=>x.goods_state).reduce((total,item)=> total+=item.goods_count,0)
    },
    checkedGoodsAmount(state){
     return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+= item.goods_count*item.goods_price,0).toFixed(2)
    }
  
  },
	mutations: {
    addToCart(state,goods){
     const findResult= state.cart.find((x)=>x.goods_id===goods.goods_id)
     // console.log(findResult)
     if(!findResult){
       state.cart.push(goods)
     }
     else{
       findResult.goods_count++
     }
     this.commit('saveToStorage')
     // console.log(state.cart)
      
    },
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    //更新购物车当中商品的勾选状态
    updateGoodsState(state,goods){
     const findResult= state.cart.find(x=>x.goods_id===goods.goods_id)
     
     if(findResult){
       findResult.goods_state=goods.goods_state
        this.commit('saveToStorage')
     }
    },
    updateGoodsCount(state,goods){
     const findResult= state.cart.find(x=>x.goods_id===goods.goods_id)
     if(findResult){
       findResult.goods_count=goods.goods_count
       this.commit('saveToStorage')
     }
    },
    //根据id删除商品
    removeGoodsById(state,goods_id){
    state.cart=  state.cart.filter(x=>x.goods_id!==goods_id)
    
    this.commit('saveToStorage')
    },
    //更新收货地址
    updateAddress(state,address){
      state.address=address
      //存储到storage
      this.commit('saveAddressToStorage')
    },
    //持久化存储address
    saveAddressToStorage(state){
      uni.setStorageSync('address',JSON.stringify(state.address))
    },
    
    //更新购物车中所有商品的勾选状态
    updateAllGoodsState(state,newState){
      state.cart.forEach(x=>x.goods_state=newState)
      
      this.commit('saveToStorage')
    },
    //更新信息
    updateUserInfo(state,userinfo){
      state.userinfo=userinfo
      this.commit('saveUserInfoToStorage')
      
    },
    //持久化存储
    saveUserInfoToStorage(state){
      uni.setStorageSync('userinfo',JSON.stringify(state.userinfo))
    }

	},

})
export default store
